package com.macro.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.HttpKit;
import com.macro.mall.common.utils.KeyedDigestMD5;
import com.macro.mall.dao.OmsOrderReturnApplyDao;
import com.macro.mall.dto.OmsOrderReturnApplyResult;
import com.macro.mall.dto.OmsReturnApplyQueryParam;
import com.macro.mall.dto.OmsUpdateStatusParam;
import com.macro.mall.mapper.OmsOrderMapper;
import com.macro.mall.mapper.OmsOrderReturnApplyMapper;
import com.macro.mall.mapper.UmsMemberStatisticsInfoMapper;
import com.macro.mall.model.*;
import com.macro.mall.service.OmsOrderReturnApplyService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 订单退货管理Service
 * Created by macro on 2018/10/18.
 */
@Service
public class OmsOrderReturnApplyServiceImpl implements OmsOrderReturnApplyService {
    @Autowired
    private OmsOrderReturnApplyDao returnApplyDao;
    @Autowired
    private OmsOrderReturnApplyMapper returnApplyMapper;
    @Autowired
    private OmsOrderMapper omsOrderMapper;
    @Autowired
    private Environment env;
    @Autowired
    private UmsMemberStatisticsInfoMapper memberStatisticsInfoMapper;
    @Override
    public List<OmsOrderReturnApply> list(OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        return returnApplyDao.getList(queryParam);
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample();
        example.createCriteria().andIdIn(ids).andStatusEqualTo(3);
        return returnApplyMapper.deleteByExample(example);
    }

    @Override
    public int updateStatus(Long id, OmsUpdateStatusParam statusParam) {
        Integer status = statusParam.getStatus();
        OmsOrderReturnApply returnApply = new OmsOrderReturnApply();
        int i = 0;
        if(status.equals(1)){
            //确认退货
            returnApply.setId(id);
            returnApply.setStatus(1);
            returnApply.setReturnAmount(statusParam.getReturnAmount());
            returnApply.setCompanyAddressId(statusParam.getCompanyAddressId());
            returnApply.setHandleTime(new Date());
            returnApply.setHandleMan(statusParam.getHandleMan());
            returnApply.setHandleNote(statusParam.getHandleNote());
            i= returnApplyMapper.updateByPrimaryKeySelective(returnApply);
        }else if(status.equals(2)){
            //完成退货
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            returnApply.setId(id);
            returnApply.setStatus(2);
            returnApply.setReceiveTime(new Date());
            returnApply.setReceiveMan(statusParam.getReceiveMan());
            returnApply.setReceiveNote(statusParam.getReceiveNote());
                OmsOrderReturnApply omsOrderReturnApply = returnApplyMapper.selectByPrimaryKey(id);
            OmsOrder omsOrder = omsOrderMapper.selectByPrimaryKey(omsOrderReturnApply.getOrderId());
            if (omsOrder.getStatus()==1){
                OmsOrder omsOrder1 = new OmsOrder();
                omsOrder1.setId(omsOrder.getId());
                omsOrder1.setStatus(4);
                omsOrderMapper.updateByPrimaryKeySelective(omsOrder1);
            }

                if (omsOrderReturnApply.getReturnAmount().doubleValue()!=0.00){
                    Map<String,Object> map = new HashMap<>();
                    map.put("account",env.getProperty("pay.account"));
                    map.put("upOrderId",omsOrder.getTongGuanSn());
                    map.put("refundMoney",omsOrderReturnApply.getReturnAmount());
                    String s = "account="+map.get("account")+"&refundMoney="+map.get("refundMoney")+"&upOrderId="+map.get("upOrderId")+"&key=39185904ef21c5881ad0ee60f12abd52";
                    map.put("sign", KeyedDigestMD5.getKeyedDigest("",s).toUpperCase());
                    String data = JSONObject.fromObject(map).toString();
                    String res = HttpKit.post(env.getProperty("pay.refundUrl"),data,headers);
                    Map<String, Object> resMap = JSON.parseObject(res,Map.class);
                    if ((int)resMap.get("status")==100 && resMap.get("state").toString().equals("5")){
                        returnApply.setPayStatus(1);
                    }else {
                        Asserts.fail("退款失败");
                    }
                }else {
                    returnApply.setPayStatus(1);
                }
            i= returnApplyMapper.updateByPrimaryKeySelective(returnApply);
            UmsMemberStatisticsInfoExample memberStatisticsInfoExample = new UmsMemberStatisticsInfoExample();
            memberStatisticsInfoExample.createCriteria().andMemberIdEqualTo(omsOrder.getMemberId());
            List<UmsMemberStatisticsInfo> umsMemberStatisticsInfos = memberStatisticsInfoMapper.selectByExample(memberStatisticsInfoExample);
            if (CollUtil.isNotEmpty(umsMemberStatisticsInfos)){
                UmsMemberStatisticsInfo memberStatisticsInfo = umsMemberStatisticsInfos.get(0);
                memberStatisticsInfo.setReturnOrderCount(memberStatisticsInfo.getReturnOrderCount()+1);
                memberStatisticsInfoMapper.insert(memberStatisticsInfo);
            }
        }else if(status.equals(3)){
            //拒绝退货
            returnApply.setId(id);
            returnApply.setStatus(3);
            returnApply.setHandleTime(new Date());
            returnApply.setHandleMan(statusParam.getHandleMan());
            returnApply.setHandleNote(statusParam.getHandleNote());
            i= returnApplyMapper.updateByPrimaryKeySelective(returnApply);
        }else{
            return 0;
        }
        return i;
    }

    @Override
    public OmsOrderReturnApplyResult getItem(Long id) {
        OmsOrderReturnApplyResult detail = returnApplyDao.getDetail(id);
        OmsOrder omsOrder = omsOrderMapper.selectByPrimaryKey(detail.getOrderId());
        detail.setOrderStatus(omsOrder.getStatus());
        return detail;
    }
}
